<?php
/**
 * Created by PhpStorm.
 * User: harlen
 * Date: 2017/2/9 0009
 * Time: 9:42
 */
namespace app\admin\controller;

use app\admin\model\ArticleCategory as ArticleCategoryModel;
use app\admin\model\Article as ArticleModel;
use think\Validate;
use thinkcms\auth\library\Tree;

class ArticleCategory extends BaseController
{
    protected $param, $id, $post, $articleModel;
    protected $url = 'articleCategory/index';
    protected $articleCategoryValidate = ['name|分类名' => 'require'];

    public function __construct(\think\Request $request)
    {

        $this->param = $request->param();
        $this->post = $request->post();
        $this->articleCategoryModel = new ArticleCategoryModel();
        $this->id = isset($this->param['id']) ? intval($this->param['id']) : '';
        parent::__construct();

    }

    /**
     * 分类列表
     * @return array
     */
    public function index()
    {
        $result = ArticleCategoryModel::where('')->order(["list_order" => "asc", 'id' => 'asc'])->column('*', 'id');
        $tree = new Tree();
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        foreach ($result as $n => $r) {
            $result[$n]['level'] = $tree->get_level($r['id'], $result);
            $result[$n]['parent_id_node'] = ($r['parent_id']) ? ' class="child-of-node-' . $r['parent_id'] . '"' : '';

            $result[$n]['str_manage'] = checkPath('articleCategory/add', ["parent_id" => $r['id']]) ? '<a href="' . url("articleCategory/add", ["parent_id" => $r['id']]) . '">添加子分类</a> |' : '';
            $result[$n]['str_manage'] .= checkPath('articleCategory/edit', ["id" => $r['id']]) ? '<a href="' . url("articleCategory/edit", ["id" => $r['id']]) . '">编辑</a> |' : '';
            $result[$n]['str_manage'] .= checkPath('articleCategory/delete', ["id" => $r['id']]) ? '<a class="a-post" post-msg="你确定要删除吗" post-url="' . url("articleCategory/delete", ["id" => $r['id']]) . '">删除</a>|' : '';
            $result[$n]['type'] = $r['type'] == 0 ? '默认分类' : '导航分类';
            $result[$n]['status'] = $r['status'] ? '开启' : '隐藏';
        }
        $str = "<tr id='node-\$id' \$parent_id_node>
                    <td style='padding-left:20px;'>
                        <input name='listorders[\$id]' type='text' size='3' value='\$list_order' data='\$id' class='listOrder'>
                    </td>
                    <td>\$id</td>
                    <td>\$spacer  \$name</td>
                    <td>\$type</td>
                    <td>\$status</td>
                    <td>\$str_manage</td>
                </tr>";

        $tree->init($result);
        $info = $tree->get_tree(0, $str);

        return $this->fetch('', ['info' => $info]);
    }

    public function add()
    {
        $parent_id = isset($this->param['parent_id']) ? $this->param['parent_id'] : '';
        if ($this->request->isPost()) {
            $post = $this->post;
            $validate = new Validate($this->articleCategoryValidate);

            if (!$validate->check($post)) {
                return ['code' => 0, 'msg' => $validate->getError()];
            }
            if ($this->articleCategoryModel->create($post)) {
                return ['code' => 1, 'msg' => lang('add success'), 'url' => url($this->url)];
            } else {
                return ['code' => 0, 'msg' => lang('add failed')];
            }
        }
        $info['selectCategorys'] = category($parent_id);

        return $this->fetch('', ['info' => $info]);
    }

    public function edit()
    {
        $id = $this->id;
        $info = $this->articleCategoryModel->get($id);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            //验证
            $validate = new Validate($this->articleCategoryValidate);

            if (!$validate->check($post)) {
                return ['code' => 0, 'msg' => $validate->getError()];
            }

            //保存数据
            if ($info->save($post)) {
                return $this->success(lang('success'), url($this->url));
            } else {
                return $this->error(lang('failed'), url($this->url));
            }
        }
        //获取分类信息
        $info['selectCategorys'] = category($info['parent_id']);

        return $this->fetch('', ['info' => $info]);
    }

    /**
     * 更新排序
     * @return array
     */
    public function order()
    {
        if ($this->request->isPost()) {
            $order = isset($this->param['order']) ? intval($this->param['order']) : '';
            $result = ArticleCategoryModel::get($this->id);

            if (empty($result)) {
                return ['code' => 0, 'msg' => lang('empty data')];
            } else if ($result) {
                if ($result->save(['list_order' => $order])) {
                    return ['code' => 1, 'msg' => lang('update success')];
                }
            }

            return ['code' => 0, 'msg' => lang('not date update')];
        }

        return ['code' => 0, 'msg' => lang('invalid request')];
    }

    /**
     * 删除
     */
    public function delete()
    {
        $id = $this->id;
        if (!$this->request->isAjax()) {
            return abort(404, lang('404 denied access'));
        }
        if (ArticleCategoryModel::destroy($id)) {
            return ['code' => 1, 'msg' => lang('delete success'), 'url'=> url($this->url)];
        } else {
            return ['code' => 0, 'msg' => lang('delete failed')];
        }
    }

    /**
     * 状态修改
     */
    public function status()
    {
        //这里的id是一个字符串
        $param = $this->param['param'];
        $id = $this->param['id'];

        if (!$this->request->isAjax()) {
            return abort(404, lang('404 denied access'));
        } else if (empty($id)) {
            return ['code' => 0, 'msg' => lang('data cannot be empty')];
        }

        $ratify = $this->articleModel->allowField(['status'])->save(['status' => $param], ['id' => ['in', $id]]);

        if ($ratify) {
            return ['code' => 1, 'msg' => lang('success'), 'url'=> url($this->url)];
        } else {
            return ['code' => 0, 'msg' => lang('failed')];
        }
    }
    /*
     * 获取子分类信息
     */
    public function getChildCategory()
    {
        $article_id = $this->param['article_id'];
        $id = $this->id;
        $info = ArticleModel::get($article_id);
        //获取到分类的路径
        $category_path = explode('|', $info->category_path);
        if(!is_array($category_path)){
            return ['$category_path'=>0, 'msg'=>lang('not category info')];
        }
        //获取子分类信息. 普通分类
        $list = ArticleCategoryModel::where(['parent_id'=>$id, 'type'=>0])->order(['list_order'=>'desc', 'id' => 'asc'])->field('id,name')->select()->toArray();
        $str = "<div class=\"col-lg-2 inline\">";
        $str .= "<select class=\"form-control text\" name=\"category_id[]\">";
        $str .= "";
        foreach($list as $r) {
            $selected = $r['selected'] = in_array($r['id'], $category_path) ? 'selected' : '';
            @extract($r);
            $str .= "<option value='". $id . "' $selected> $name </option>";
        }
        $str .= "</select></div>";
        return $str;
    }
}